-- ======================================================================
-- Hell Logic Sniffer Addon 
-- 
-- Copyright 2016 Hell-Prototypes
--
-- http://www.hellprototypes.com/
-- ======================================================================
ModuleClass = "LS_PLUGIN"
ModuleName  = "MoveCursorByEdgeCount"
ModuleTip   = "Move Right Cursor By Edge Count"

VAR_EDGE_COUNT = "MoveCursorByEdgeCount_VAR_EDGE_COUNT"

g_cursor_offset = -1

function get_edge_count()
	local last = LS_API.ReadVariable(VAR_EDGE_COUNT)
	if not last then last = 5 end

	local edge_count = LS_API.InputBox(last, "Input Edge Count")
    if edge_count == nil then
		return 0
    end

	if last ~= edge_count then
		LS_API.SaveVariable(VAR_EDGE_COUNT, edge_count)
	end

	return edge_count
end

function get_current_channel()
	local param = LS_API.GetCommonParameter()
	if #param < 4 then
		return -1
	end
	g_cursor_offset = param[3] --left
	return param[4]
end

function get_edge_list(channel_data)
	local rawdata_index = 1

	local last = channel_data[1]
	local edge_list = {}
	local pulse_list_idx = 1
	while rawdata_index <= #channel_data do
		edge_list[pulse_list_idx] = channel_data[rawdata_index]
		rawdata_index = rawdata_index + 2
		pulse_list_idx = pulse_list_idx + 1
	end
	
	return edge_list
end


function main ()
	local current_channel = get_current_channel()
	if current_channel < 0 then
		LS_API.MessageBox("Please select one channel")
		return
    end

	local channel_data = LS_API.GetChannelData(current_channel)
    if type(channel_data) ~= "table" then
		LS_API.MessageBox("No data found in channel : " .. current_channel)
		return
	end

	local edge_list = {}
	
	local edge_count = get_edge_count()
	if edge_count == 0 then
		return
	else
		edge_list = get_edge_list(channel_data)
		if edge_count > 0 then
			if g_cursor_offset < edge_list[1] then
				g_cursor_offset = edge_list[1]
			end
		else
			if g_cursor_offset > edge_list[#edge_list] then
				g_cursor_offset = edge_list[#edge_list]
			end
		end
	end

	if edge_count > 0 then
		for i=1, #edge_list do
			if edge_list[i] >= g_cursor_offset then
				if i + edge_count <= #edge_list then
					LS_API.MoveRightCursorTo(edge_list[i+ edge_count])
				else
					--LS_API.MoveRightCursorTo(edge_list[#edge_list])
					LS_API.MessageBox("Out of range >>> ...")
				end
				break
			end
		end
	else
		for i=#edge_list, 1, -1 do
			--LS_API.ReportPushBack("pulse_list[i].time " .. pulse_list[i].time)
			if edge_list[i] <= g_cursor_offset then
				if i + edge_count >= 0 then
					LS_API.MoveRightCursorTo(edge_list[i+ edge_count])
				else
					--LS_API.MoveRightCursorTo(edge_list[#edge_list])
					LS_API.MessageBox("Out of range <<< ...")
				end
				break
			end
		end
	end
end

